import http from 'wechat-http'

http.baseURL = 'https://live-api.itheima.net/'

let app = null
http.intercept.request = (config) => {
  if (!app) app = getApp()
  if (app.token) {
    if (config.header) {
      config.header.Authorization = 'Bearer ' + app.token
    } else config.header = { Authorization: 'Bearer ' + app.token }
  }
  return config
}

http.intercept.response = (res) => {
  if (res.statusCode.toString().startsWith('2')) {
    if (res.data.code !== 10000) {
      wx.utils.toast(res.data.message)
      return Promise.reject(res)
    }
    return res
  } else if (res.statusCode === 401) {
    return new Promise((resolve, reject) => {
      wx.request({
        method: 'post',
        url: wx.http.baseURL + '/refreshToken',
        header: {
          Authorization: 'Bearer ' + app.refreshToken,
        },
        success: (res2) => {
          if (res2.statusCode.toString().startsWith('2')) {
            const { token, refreshToken } = res2.data.data
            app.setToken(token)
            app.setRefreshToken(refreshToken)
            resolve(wx.http(res.config))
          } else {
            wx.utils.skipLogin()
          }
        },
        fail: (err) => {
          wx.utils.skipLogin()
          reject(err)
        },
      })
    })
  } else {
    return Promise.reject(res)
  }
}

export default http
wx.http = http
